package cn.wolfcode.chatroom.core;

import cn.wolfcode.chatroom.core.domain.ChatroomMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Date;

/**
 * 1. 能够进行用户认证
 * 2. 统计在线人数
 * 3. 页面要实时展示所有消息
 * 4. 页面需要区分不同类型的消息
 */
public class ChatroomHandler extends TextWebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String username = SessionContext.getUsername(session);
        SessionContext.addSession(session);
        System.out.println(new Date().toLocaleString() + " 用户上线：" + username + " 当前在线人数：" + SessionContext.getOnlineNum());

        ChatroomMessage message = new ChatroomMessage();
        message.setType(ChatroomMessage.SYSTEM);

        message.setContent(username + " 用戶上线了.");
        message.setOnlineNum(SessionContext.getOnlineNum());
        SessionContext.sendMsg(message);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("session.getId() = " + session.getId());
        System.out.println("message.getPayloadLength() = " + message.getPayloadLength());
        System.out.println("message.getPayload() = " + message.getPayload());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String username = SessionContext.getUsername(session);
        SessionContext.removeSession(session);
        System.out.println(new Date().toLocaleString() + " 用户下线：" + username + " 当前在线人数：" + SessionContext.getOnlineNum());

        ChatroomMessage message = new ChatroomMessage();
        message.setType(ChatroomMessage.SYSTEM);
        message.setContent(username + " 用戶下线了.");
        message.setOnlineNum(SessionContext.getOnlineNum());
        SessionContext.sendMsg(message);
    }


}
